import axios from 'axios'
import Vue from 'vue'
import router from '@/router'
// import Router from 'vue-router'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
// Vue.use(Router)
// const originalPush = Router.prototype.push
// Router.prototype.push = function push (location) {
//     return originalPush.call(this, location).catch(err => err)
// }
const Qs = require('qs');

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    if (store.getters.token) {

      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
    }
    // config.headers['Content-Type'] = "charset=UTF-8"
    // application/json;
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
      
async function logout(){
  await store.dispatch("user/logout")
  router.push(`/login`)
}

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if(res.msg=="您已离线，请重新登陆 "){
      logout()
      // store.dispatch("user/logout")
      return
    }
    return res
    // if (res.status !== 0) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

function request(url, data = {},method='post') {
  if(method=='get'){
    return service({
      url,
      method,
      params:({
        user: localStorage.username,
        sid: localStorage.sid,
        ...data
      })
    })
  }
  if(method=='post'){
    return service({
      url,
      method,
      data: Qs.stringify({
        user: localStorage.username,
        sid: localStorage.sid,
        ...data
      })
    })
  }

}

export function requestMock(url, data = {}, method = 'post') {
  return service({
    url,
    method,
    data
  })
}

export default request
